﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSCore;
using CSCore.Codecs.WAV;
using CSCore.MediaFoundation;
using CSCore.SoundIn;
using CSCore.Streams;
using FM.Common;
using FM.Events;
using FM.Services;
using FM.录音.Data;
using FM.录音.Events;
using FM.录音.接口;
using FM.接口;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;
using NJT.IO;

namespace FM.录音.Services
{
    public class 录音服务mp3 : 启动基类, I录音服务
    {
        public 录音服务mp3(IUnityContainer 人事部cs, IEventAggregator 新闻部cs, IRegionManager 模块cs)
            : base(人事部cs, 新闻部cs, 模块cs)
        {
            新闻部.GetEvent<退出Event>().Subscribe(退出Action, true);
        }


        public int ID { get; set; }
        public IFm录音配置 录音配置 { get; set; }
        public bool Is录音中 { get; set; }
        public void Set录音(bool 录音)
        {
        }



        private void 退出Action(object obj)
        {
             停止录音();
        }

        private bool _is录音中;
        private WasapiCapture _输入声卡;

        //public override void 启动()
        //{
        //    base.启动();
        //    //新闻部.GetEvent<信号录音Event>().Subscribe(信号录音Action, true);
        //}

        private void 信号录音Action(bool obj)
        {
            if (obj)
            {
                开始录音();
            }
            else
            {
                停止录音();
            }
        }

        //private IFm录音配置 录音配置;
        private void 开始录音()
        {
            _is录音中 = true;
            if (录音配置 == null)
            {
                录音配置 = new Fm录音配置1();
            }
            var 声卡1 = 声卡设备.查找输入声卡(录音配置.录音声卡);
            if (声卡1 == null)
            {
                新闻部.GetEvent<状态栏更新Event>().Publish(new 状态栏Data1(Enum状态栏.提示, "没有输入声卡"));
                log.Log("没有输入声卡", Category.Exception, Priority.High);
                return;
            }

            _输入声卡 = null;
            _输入声卡 = new WasapiCapture { Device = 声卡1 };
            _输入声卡.Initialize();

            var 目录名 = 目录.目录合并(录音配置.录音目录, DateTime.Now.ToString(运行状态.日期目录格式));
            if (!目录.目录检查并建立(目录名))
            {
                log.Log("无法创建目录:", Category.Warn, Priority.High);
                return;
            }

            var 文件名 = 目录.目录合并(目录名, DateTime.Now.ToString(运行状态.文件名格式)) + ".mp3";

            log.Log("记录文件:" + 文件名, Category.Info, Priority.High);

            var wasapiCaptureSource = new SoundInSource(_输入声卡);
            var stereoSource = wasapiCaptureSource.ToStereo();

            //建立可共享的文件流
            Stream 文件流 = new FileStream(文件名, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            
            var writer = MediaFoundationEncoder.CreateMP3Encoder(stereoSource.WaveFormat,
                    文件流, 320000);
            _输入声卡.Stopped += (s, e) =>
            {
                if (writer != null)
                    writer.Dispose();
            };
            byte[] buffer = new byte[stereoSource.WaveFormat.BytesPerSecond];
            wasapiCaptureSource.DataAvailable += (s, e) =>
            {
                if (_is录音中 && writer != null && stereoSource != null)
                {
                    int read = stereoSource.Read(buffer, 0, buffer.Length);
                    writer.Write(buffer, 0, read);
                }
            };

            _输入声卡.Start();
        }

     
        private void 停止录音()
        {
            _is录音中 = false;
            log.Log("停止记录文件", Category.Info, Priority.Low);
            Task.Factory.StartNew(() =>
            {
                try
                {
                    if (_输入声卡 != null)
                    {
                        _输入声卡.Stop();
                    }
                }
                catch (Exception)
                {
                    throw;
                }

              
            }
        );

        }

       
    }
}